﻿using System;
using System.Collections.Generic;
using Framework.Base;
using UnityEditor.SceneManagement;

namespace Framework.ECS
{
    public class BaseEntity: BaseObject, IPoolObj
    {

        /// <summary>
        ///  事件对象
        /// </summary>
        public readonly Event.Event eventObj = new Event.Event();

        private readonly Dictionary<Type,BaseComponent> m_componentDict = new Dictionary<Type, BaseComponent>();

        public T AddComponent<T>() where T:BaseComponent
        {
            var component = PoolMgr.Create<T>();
            m_componentDict[typeof(T)] = component;
            component.entity = this;
            component.OnStart();
            return component;
        }

        public void RemoveComponent<T>()
        {
            var type = typeof(T);
            if (m_componentDict.TryGetValue(type,out var comp))
            {
                PoolMgr.Recycle(comp);
                this.m_componentDict.Remove(type);
                
            }
        }

        public void RemoveComponent(BaseComponent component)
        {
            var type = component.GetType();
            if (m_componentDict.ContainsKey(type))
            {
                PoolMgr.Recycle(component);
                this.m_componentDict.Remove(type);
                   
            }
            else
            {
                throw new Exception("remove Component error");
            }
        }

        public void RemoveAllComponent()
        {
            foreach (var pair in m_componentDict)
            {
                PoolMgr.Recycle(pair.Value);
            }

            this.m_componentDict.Clear();
        }
        
        

        public void OnFetch()
        {
            
        }

        public void OnRecycle()
        {
            this.RemoveAllComponent();
        }
    }
}